const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
    showMsg
} from '../../../../utils/config.js'
import {
    reqDeviceUsergetByImei,
    reqGetNormalUser,
    reqDeviceUserbind,
    reqDeviceUserunBind,
    reqAddNormalUser,
} from '../../../../request/api'
import {
    checkRegNo,
    validateMobile,
} from '../../../../utils/validate.js'

Page({
    data: {
        x: '580rpx',
        y: '1000rpx',
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        dataList: [],
        page: 1,
        searchValue: '', //输入的搜索值
        isNextPage: true, //是否下一页
        triggered: false, //是否下拉刷新列表
        show: false,
        showPopup: false,

        info: {},
        ownerStr: '',
        mobile: "",
        nickname: "",
        idCard: "",
        ownerflag: false,
        showSucceed:false,
        isEdit:false,
    },

    onLoad(e) {
        console.log(JSON.parse(e.info));
        this.setData({
            info: JSON.parse(e.info)
        })
    },
    onShow() {
        this.getDeviceUsergetByImei() // 设备查询设备用户
    },
    // 设备查询设备用户
    async getDeviceUsergetByImei() {
        const res = await reqDeviceUsergetByImei(this.data.info.imei)
        if (res.code !== 20000) return showMsg(res.message)
        console.log(res);
        this.setData({
            dataList: res.data.rows || []
        })
    },
    // 获取手机号
    handleInput(e) {
        this.setData({
            'mobile': e.detail.value
        })
        if (e.detail.value.length == 11) {
            if (!validateMobile(this.data.mobile)) return
            this.getGetNormalUser(e.detail.value)
        }
    },
    // 查询业主账号
    async getGetNormalUser(mobile) {
        const res = await reqGetNormalUser({
            mobile: mobile
        })
        console.log(res);
        if (res.code !== 20000) return showMsg(res.message)
        if(res.data.row==null || res.data.row==''){
            // 业主不存在
            this.setData({
                showPopup: true,
                isEdit:false,
            })
            return;
        }

        this.setData({
            ownerStr: res.data.row || '',
            ownerflag: false
        })
    },
    handlenickname(e){
        this.setData({
            'nickname': e.detail.value
        })
    },
    handleidCard(e){
        this.setData({
            'idCard': e.detail.value
        })
    },
    onClose2() {
        this.setData({
            showPopup: false,
            mobile: "",
            ownerStr:""
        })
    },
    onbindtap() {
        this.setData({
            showPopup: false,
            ownerflag: true, //新增业主+关联
            ownerStr:""
        })
    },
    // 清除手机号
    mobileClear() {
        this.setData({
            mobile: "",
            ownerStr: '',
        })
    },
    nicknameClear(){
        this.setData({
            nickname: "",
        })
    },
    idCardClear(){
        this.setData({
            idCard: "",
        })
    },
    // 滚动到底部触发
    lower() {
    },
    // 去新增
    goAddAlarmReceiver() {
        this.setData({
            show: true,
            mobile: "",
            nickname: "",
            idCard: "",
            ownerStr: '',
            ownerflag: false
        })
    },
    // 去详情
    goDetail(e) {
        // let {
        //     item
        // } = e.currentTarget.dataset
        // let info = JSON.stringify(item)
        // wx.navigateTo({
        //     url: `/pages/index-inside-page/alarm-receiver-detail/alarm-receiver-detail?item=${info}`,
        // })
    },
    // 点击删除
    clickDelete(e) {
        console.log(e.currentTarget.dataset.id);
        Dialog.confirm({
                title: '温馨提示',
                message: '此操作将取消关联，是否继续？',
            })
            .then(async () => {
                const res = await reqDeviceUserunBind(e.currentTarget.dataset.id)
                if (res.code != 20000) return showMsg(res.message);
                showMsg("操作成功")
                this.getDeviceUsergetByImei()
            })
            .catch(() => {});
    },
    onClose() {
        this.setData({
            show: false,
            ownerStr:""
        });
    },
    // 确定
    async bindtapShoudon() {
        if (!this.data.mobile) return showMsg("请输入业主手机号")
        if (!validateMobile(this.data.mobile)) return
        if (this.data.ownerflag) {
            // 新增业主并关联
            this.getAddNormalUser()
        } else {
            // 关联逻辑
            this.reqAddDevice()
        }
    },
       // 新增业主并关联
    async getAddNormalUser(){
        if (!this.data.nickname) return showMsg("请输入真实姓名")
        if (!checkRegNo(this.data.idCard)) return
        const res = await reqAddNormalUser({
            nickname: this.data.nickname,
            mobile: this.data.mobile,
            idCard: this.data.idCard,
        })
        if (res.code != 20000) return showMsg(res.message);
        console.log(res);
        const restr = await reqGetNormalUser({
            mobile: this.data.mobile,
        })
        if (restr.code != 20000) return showMsg(restr.message);
        console.log(restr);

        const restrs = await reqDeviceUserbind({
            userId: restr.data.row.id,
            imei:this.data.info.imei
        })
        if (restrs.code != 20000) return showMsg(restrs.message);
        console.log(restrs);
        // showMsg("操作成功")
        this.onClose()
        this.setData({
            showSucceed:true
        })
    },
    // 确定
    onSucceed(){
        this.setData({
            showSucceed:false
        })
        this.getDeviceUsergetByImei() // 设备查询设备用户
    },
      // 关联逻辑
    async reqAddDevice() {
        // 业主绑定设备|| 设备绑定业主
        const res = await reqDeviceUserbind({
            userId: this.data.ownerStr.id,
            imei: this.data.info.imei,
        })
        if (res.code == 14010) {
            showMsg('已关联该业主');
            return
        }
        if (res.code != 20000) return showMsg(res.message);
        showMsg("关联成功")
        this.onClose()
        this.getDeviceUsergetByImei() // 设备查询设备用户
    },
})